package com.ts.flash;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class LightActivity extends Activity {
    private Button mLightBtn = null;
    private Camera mCamera = null;
    private Parameters mParameters = null;
    public static boolean mIsOn = false;
    private int mBackCount = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.light_layout);

        mLightBtn = (Button) findViewById(R.id.btn_light);
        mLightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mIsOn) {
                    mLightBtn.setBackgroundResource(R.drawable.shou_on);
                    mCamera = Camera.open();
                    mParameters = mCamera.getParameters();
                    mParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);// 开启
                    mCamera.setParameters(mParameters);
                    mIsOn = true;
                } else {
                    mLightBtn.setBackgroundResource(R.drawable.shou_off);
                    mParameters.setFlashMode(Parameters.FLASH_MODE_OFF);// 关闭
                    mCamera.setParameters(mParameters);
                    mCamera.release();
                    mIsOn = false;
                }
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mBackCount++;
            switch (mBackCount) {
                case 1:
                    Toast.makeText(LightActivity.this, getString(R.string.again_exit), Toast.LENGTH_SHORT).show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mBackCount = 0;
                        }
                    }, 2000);
                    break;
                case 2:
                    mBackCount = 0;
                    closeApp();
                    break;
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void closeApp() { // 关闭程序
        if (mIsOn) {// 开关打开时,release相机
            mCamera.release();
            mIsOn = false;// 避免，打开开关后退出程序，再次进入不打开开关直接退出时，程序错误
        }
        LightActivity.this.finish();
        android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程
    }
}
